package com.cxs.shopstore.utils;

import com.cxs.shopstore.models.Car;
import com.cxs.shopstore.models.Good;
import com.cxs.shopstore.models.User;
import org.springframework.stereotype.Component;
import org.springframework.util.FileCopyUtils;

import java.io.File;
import java.io.IOException;
import java.util.Base64;
import java.util.List;

/*
 * @Author:cxs
 * @Date:2021/5/9  12:00
 * @Version 1.0
 * 图片地址留存
 * */
@Component
public class ImgUtils {
    //商品批量图片处理
    public List<Good> imgPathToBase64String(List<Good> goodList){
        if(goodList != null && goodList.size() > 0){
            try {
                for (Good good : goodList) {
                    if(good.getGoodImgPath() != null && good.getGoodImgPath() != ""){
                        good.setImgBase64(Base64.getEncoder().encodeToString(FileCopyUtils.copyToByteArray(new File(good.getGoodImgPath()))));
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return goodList;
    }
    //用户头像处理
    public User imgPathToBase64String(User user){
        if(user.getUserImg() != null && user.getUserImg() != ""){
            try {
                user.setImgBase64(Base64.getEncoder().encodeToString(FileCopyUtils.copyToByteArray(new File(user.getUserImg()))));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return user;
    }

    public List<Car> imgToBase64String(List<Car> carList){
        if(carList != null && carList.size() > 0){
            try {
                for (Car car : carList) {
                    Good good = car.getGood();
                    good.setImgBase64(Base64.getEncoder().encodeToString(FileCopyUtils.copyToByteArray(new File(good.getGoodImgPath()))));
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return carList;
    }

}
